<?php
namespace Helper\Controller;

use Think\Controller;

class UeditorController extends Controller {

    const SAVE_PATH = 'ueditor';

    protected $upload_setting;

    function _initialize() {
        $admin_id = x_get_admin_id();
        $user_id  = x_get_user_id();
        if (empty($admin_id) && empty($user_id)) {
            exit("非法上传");
        }
        $this->upload_setting = x_get_upload_setting();
    }

    function upload() {
        date_default_timezone_set("Asia/chongqing");
        error_reporting(E_ERROR);
        header("Content-Type: text/html; charset=utf-8");
        $action = I('get.action');

        switch ($action) {
            case 'config':
                $result = $this->_set_config();
                break;
            /* 上传图片 */
            case 'uploadimage':
                /* 上传涂鸦 */
            case 'uploadscrawl':
                $result = $this->_upload('image');
                break;
            /* 上传视频 */
            case 'uploadvideo':
                $result = $this->_upload('video');
                break;
            /* 上传文件 */
            case 'uploadfile':
                $result = $this->_upload('file');
                break;

            /* 列出图片 */
            case 'listimage':
                $result = "";
                break;
            /* 列出文件 */
            case 'listfile':
                $result = "";
                break;

            /* 抓取远程文件 */
            case 'catchimage':
                $result=$this->_get_remote_image();
                break;

            default:
                $result = json_encode(array('state'=> '请求地址出错'));
                break;
        }

        /* 输出结果 */
        if (isset($_GET["callback"]) && false ) {//TODO 跨域上传
            if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
                echo htmlspecialchars($_GET["callback"]) . '(' . $result . ')';
            } else {
                echo json_encode(array(
                    'state'=> 'callback参数不合法'
                ));
            }
        } else {
            exit($result) ;
        }
    }


    private function _set_config()
    {
        $CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "",
            file_get_contents(C('TMPL_PARSE_STRING.__ROOT__') . 'public/lib/ueditor/config.json')), true);

        $CONFIG['imageMaxSize']    =  $this->upload_setting['image']['upload_max_filesize'] * 1024;
        $CONFIG['scrawlMaxSize']   =  $this->upload_setting['image']['upload_max_filesize'] * 1024;
        $CONFIG['imageAllowFiles'] = array_map(array($this, '_extension'), explode(",", $this->upload_setting['image']['extensions']));

        $CONFIG['catcherMaxSize']    =  $this->upload_setting['image']['upload_max_filesize'] * 1024;
        $CONFIG['catcherAllowFiles'] = array_map(array($this, '_extension'), explode(",", $this->upload_setting['image']['extensions']));

        $CONFIG['videoMaxSize']    =  $this->upload_setting['video']['upload_max_filesize'] * 1024;
        $CONFIG['videoAllowFiles'] = array_map(array($this, '_extension'), explode(",", $this->upload_setting['video']['extensions']));

        $CONFIG['fileMaxSize']    =  $this->upload_setting['file']['upload_max_filesize'] * 1024;
        $CONFIG['fileAllowFiles'] = array_map(array($this, '_extension'), explode(",", $this->upload_setting['file']['extensions']));

        return json_encode($CONFIG);
    }

    private function _extension($str) {
        return '.' . trim($str, '.');
    }

    private function _upload($filetype = 'image') {

        $result = A('Helper/Upload')->uploadFile(self::SAVE_PATH, $filetype);
        $response = array(
            "state"    => empty($result['status']) ? $result['message'] :'SUCCESS',
            "url"      => empty($result['url']) ? '' : $result['url'],
            "title"    => empty($result['name']) ? '' : $result['name'],
            "original" => empty($result['name']) ? '' : $result['name'],
        );

        return json_encode($response);

    }


}